package Undo
{
	import flash.events.Event;
	import flash.events.FocusEvent;
	
	import mx.controls.ComboBox;
	import mx.core.UIComponent;

	public class ComboBoxUndoAdapter implements IUndoAdapter
	{
		private var myField:ComboBox;
		private var undoStack:UndoStack;
		
		private var fieldValueBeforeChange:int;
		
		public static function listenTo(object:UIComponent, stack:UndoStack) : IUndoAdapter
		{
			var field:ComboBox = object as ComboBox;
			return (field && stack && !field.editable)? new ComboBoxUndoAdapter(field, stack) : null;
		}
		
		public function listenTo(object:UIComponent, stack:UndoStack) : IUndoAdapter
		{
			return ComboBoxUndoAdapter.listenTo(object, stack);
		}
		
		public function ComboBoxUndoAdapter(field:ComboBox, stack:UndoStack)
		{
			this.myField = field;
			this.undoStack = stack;

			field.addEventListener(FocusEvent.FOCUS_IN, this.saveFieldValue);
			field.addEventListener(Event.CHANGE, this.fieldChange);
		}
		
		public function unlisten() : void
		{
			this.myField.removeEventListener(FocusEvent.FOCUS_IN, this.saveFieldValue);
			this.myField.removeEventListener(Event.CHANGE, this.fieldChange);

			this.undoStack = null;
			this.myField = null;
		}
		
		public function getListened() : UIComponent
		{
			return this.myField;
		}
	
		private function saveFieldValue(event:FocusEvent) : void
		{
			this.fieldValueBeforeChange = myField.selectedIndex;
		}
		
		private function fieldChange(event:Event) : void
		{
			var after:Object = {index:this.myField.selectedIndex};
			var before:Object = {index:this.fieldValueBeforeChange};
			this.undoStack.push(new UndoEvent(this.myField, this, before, after));
			this.saveFieldValue(null);
		}

		public function reverse(after:Object, before:Object) : Boolean
		{
			if (!this.myField.visible || !this.myField.enabled) return false;
			this.myField.setFocus();
			this.myField.selectedIndex = before.index;
			this.saveFieldValue(null);
			return true;
		}
		
	}
}